﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Web.UI.WebControls;
using mojoPortal.Web;
using mojoPortal.Web.Framework;
using mojoPortal.Web.UI;
using mojoPortal.Business;
using eStore.Business;
using Resources;

namespace eStore.UI
{
    public partial class AdminCategoryEditPage : mojoBasePage
    {
        private int pageId = -1;
        private int moduleId = -1;
        private int categoryID = -1;
        protected eStoreConfiguration config = new eStoreConfiguration();
        readonly eStoreDB repository = new eStoreDB();

        protected void Page_Load(object sender, EventArgs e)
        {

            if (!UserCanEditModule(moduleId))
            {
                SiteUtils.RedirectToAccessDeniedPage();
                return;
            }

            LoadSettings();


            SetupCss();
            PopulateLabels();
            PopulateControls();

        }

        private void PopulateControls()
        {
            if (Page.IsPostBack) return;
            PopulateRootCategories();
            PopulateData();
        }

        private void PopulateData()
        {
            if (categoryID > 0)
            {
                ud_eStoreCategory currentCategory = repository.GeteStoreCategoryByCatID(categoryID);
                lbCategoryParent.Items.FindByValue(currentCategory.ParentID.ToString()).Selected = true;
                txtName.Text = currentCategory.Name;
            }
            else
            {
                lbCategoryParent.SelectedIndex = 0;
            }
        }

        private void PopulateRootCategories()
        {
            lbCategoryParent.DataSource = repository.GeteStoreRootCategoriesByModuleID(moduleId);
            lbCategoryParent.DataTextField = "Name";
            lbCategoryParent.DataValueField = "CategoryID";
            lbCategoryParent.DataBind();
            lbCategoryParent.Items.Remove(lbCategoryParent.Items.FindByValue(categoryID.ToString()));
            PopulateChildNode(lbCategoryParent);
            lbCategoryParent.Items.Insert(0, new ListItem(eStoreResources.ParentCategoryChoose, "0"));
        }

        private void PopulateChildNode(ListBox root)
        {
            for (int i = 0; i < root.Items.Count; i++)
            {
                List<ud_eStoreCategory> children = repository.GeteStoreChildCategoryByCatID(int.Parse(root.Items[i].Value));
                if (children.Count <= 0) continue;
                string prefix = string.Empty;
                while (root.Items[i].Text.StartsWith("-"))
                {
                    prefix += root.Items[i].Text.Substring(0, 3);
                    root.Items[i].Text = root.Items[i].Text.Remove(0, 3);
                }
                root.Items[i].Text = prefix + root.Items[i].Text;
                foreach (ud_eStoreCategory child in children)
                {
                    if (child.CategoryID.Equals(categoryID)) continue;
                    ListItem list = new ListItem
                                        {
                                            Text = prefix + @"---" + child.Name,
                                            Value = child.CategoryID.ToString()
                                        };
                    root.Items.Insert(root.Items.IndexOf(root.Items[i]) + 1, list);
                }
            }
        }

        private void Save()
        {
            if (categoryID.Equals(-1))
            {
                Insert();
            }
            else
            {
                Update();
            }
            WebUtils.SetupRedirect(this, SiteRoot + "/eStore/AdminCategory.aspx?pageid=" + pageId + "&mid=" + moduleId);
        }

        private void Insert()
        {
            repository.InserteStoreCategory(moduleId, txtName.Text, int.Parse(lbCategoryParent.SelectedValue));
        }

        private void Update()
        {
            repository.UpdateeStoreCategory(categoryID, moduleId, txtName.Text, int.Parse(lbCategoryParent.SelectedValue));
        }

        private void PopulateLabels()
        {
            lnkStoreMenu.Text = eStoreResources.StoreManagerHeading;
            lnkStoreMenu.NavigateUrl = SiteRoot + "/eStore/AdminDashboard.aspx?pageid="
                                       + pageId.ToString(CultureInfo.InvariantCulture)
                                       + "&mid=" + moduleId.ToString(CultureInfo.InvariantCulture);

            lnkAdminCategory.Text = eStoreResources.CategoryAdministrationLink;
            lnkAdminCategory.NavigateUrl = SiteRoot + "/eStore/AdminCategory.aspx?pageid="
                                       + pageId.ToString(CultureInfo.InvariantCulture)
                                       + "&mid=" + moduleId.ToString(CultureInfo.InvariantCulture);

            lnkCurrentPage.Text = eStoreResources.CategoryEditLink;
            lnkCurrentPage.NavigateUrl = Request.Url.ToString();

            Title = SiteUtils.FormatPageTitle(siteSettings, eStoreResources.ProductEditHeading);
            ltrTitle.Text = eStoreResources.CategoryEditLink;
            btnSave.Text = eStoreResources.StoreSettingsSaveButton;
        }

        private void LoadSettings()
        {

            if (CurrentPage.ContainsModule(moduleId))
            {
                //store = StoreHelper.GetStore(siteSettings.SiteGuid, moduleId);
                Hashtable moduleSettings = ModuleSettings.GetModuleSettings(moduleId);
                config = new eStoreConfiguration(moduleSettings);

            }

            try
            {
                // this keeps the action from changing during ajax postback in folder based sites
                SiteUtils.SetFormAction(Page, Request.RawUrl);
            }
            catch (MissingMethodException)
            {
                //this method was introduced in .NET 3.5 SP1
            }

        }

        private void LoadParams()
        {
            pageId = WebUtils.ParseInt32FromQueryString("pageid", pageId);
            moduleId = WebUtils.ParseInt32FromQueryString("mid", moduleId);
            categoryID = WebUtils.ParseInt32FromQueryString("catid", categoryID);
        }

        protected virtual void SetupCss()
        {
            // older skins have this
            if (Page.Master == null) return;
            StyleSheet stylesheet = (StyleSheet)Page.Master.FindControl("StyleSheet");
            if (stylesheet == null) return;
            if (stylesheet.FindControl("styleestore") != null) return;
            Literal cssLink = new Literal
            {
                ID = "styleestore",
                Text = @"<link href='"
                       + SiteUtils.GetSkinBaseUrl()
                       + @"styleestore.css' type='text/css' rel='stylesheet' media='screen' />"
            };

            stylesheet.Controls.Add(cssLink);
        }

        void btnSave_Click(object sender, EventArgs e)
        {
            Save();
        }
        private void LoadPanels()
        {
            Hashtable settings = ModuleSettings.GetModuleSettings(moduleId);
            config = new eStoreConfiguration(settings);
            LoadSideContent(false, false, true, true, 0);
        }
        #region OnInit



        protected override void OnPreInit(EventArgs e)
        {
            AllowSkinOverride = true;
            base.OnPreInit(e);
        }



        protected override void OnInit(EventArgs e)
        {
            LoadParams();
            LoadPanels();

            base.OnInit(e);

            Load += Page_Load;
            btnSave.Click += btnSave_Click;
        }


        #endregion
    }
}
